package com.ckzp.weixin;

import com.alibaba.fastjson.JSON;
import com.ckzp.core.Results;
import com.ckzp.core.id.UUIDHex;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.util.HtmlUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.plugins.UpImage;
import com.ckzp.weixin.model.WxUserToken;
import com.jfinal.kit.HttpKit;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 51594 on 2022/8/15.
 */
public class AppTool {


    /**
     * 根据 CODE取得用户的OPENID
     * <p/>
     * https://api.weixin.qq.com/sns/jscode2session?appid=&secret=&js_code=&grant_type=authorization_code
     *
     * @param code
     * @return
     */
    public static WxUserToken getWxAppToken(String code) {
        String url = "";
        try {
            code = HtmlUtil.decode(code);
            String appid = WxTool.getAppAppID();
            String appsecret = WxTool.getAppAppSecret();
            url = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "" +
                    "&grant_type=authorization_code";
            String result = HttpKit.get(url);
            Object o = JSON.parseObject(result, WxUserToken.class);
            if (o instanceof WxUserToken) {
                return (WxUserToken) o;
            } else {
                return new WxUserToken().setErrcode("9").setErrmsg("未知");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new WxUserToken().setErrcode("9").setErrmsg(e.getMessage());
        }
    }


    /**
     * 根据 CODE取得用户的OPENID
     * <p/>
     * https://api.weixin.qq.com/sns/jscode2session?appid=&secret=&js_code=&grant_type=authorization_code
     *
     * @param code
     * @return
     */
    public static WxUserToken getWxAppToken2(String code) {
        String url = "";
        try {
            code = HtmlUtil.decode(code);
            String appid = WxTool.getAppAppID2();
            String appsecret = WxTool.getAppAppSecret2();
            url = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "" +
                    "&grant_type=authorization_code";
            String result = HttpKit.get(url);
            Object o = JSON.parseObject(result, WxUserToken.class);
            if (o instanceof WxUserToken) {
                return (WxUserToken) o;
            } else {
                return new WxUserToken().setErrcode("9").setErrmsg("未知");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new WxUserToken().setErrcode("9").setErrmsg(e.getMessage());
        }
    }


    /**
     * 检查一段文本是否含有违法违规内容。
     *
     * @param openid
     * @param content
     * @return
     */
    public static Results msgSecCheck(String openid, String content) {
        String ACCESS_TOKEN = AccessTokenTool.getAppAccessToken();
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + ACCESS_TOKEN;
        Jmode data = Jmode.n()
                .set("openid", openid)
                .set("scene", 2)
                .set("version", 2)
                .set("content", content);
        Map<String, String> headers = new HashMap<String, String>(16);
        headers.put("Content-Type", "application/json");
        String result = HttpKit.post(url, null, data.toJson(), headers);
        Map o = JSON.parseObject(result, Map.class);
        if ("0".equals(StringUtil.getString(o, "errcode"))) {
            Map res = (Map) o.get("result");
            if ("pass".equals(StringUtil.getString(res, "suggest"))) {
                return Results.n().setMsg(data.toJson()).setMessage(o.toString());
            }
        }
        return Results.n(9).setMsg(data.toJson()).setMessage(o.toString());
    }

    /**
     * 取得手机号
     *
     * @param code
     * @return
     */
    public static JsonResult getPhoneNumber(String code) {
        String phonenumber = "";
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + AccessTokenTool.getAccessToken();
        Jmode data = Jmode.n().set("code", code);
        Map<String, String> headers = new HashMap<String, String>(16);
        headers.put("Content-Type", "application/json");
        String result = HttpKit.post(url, null, data.toJson(), headers);
        Map o = JSON.parseObject(result, Map.class);
        if ("0".equals(StringUtil.getString(o, "errcode"))) {
            Map phone_info = (Map) o.get("phone_info");
            if (phone_info != null) {
                phonenumber = StringUtil.getString(phone_info, "phoneNumber");
            }
            return JsonResult.n().setData(phonenumber);
        } else {
            return JsonResult.n().setCode(9).setData(result);
        }
    }


    /**
     * 取小程序 推广二唯码
     * 并保存到本地
     * 不限次数
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
     *
     * @param page        页面 page/index/index
     * @param secne       参数 {pid:1,aid:2}
     * @param path        保存路经
     * @param env_version 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
     * @param is_hyaline
     * @return
     */
    public static String getAppQrCodePath(String page, String secne, String path, String env_version, boolean is_hyaline) {
        String savepath = UpImage.IMAGE_SAVE_PATH + path;
        Jmode data = Jmode.n().set("page", page).set("scene", secne).set("is_hyaline", is_hyaline).set("env_version", env_version).set("check_path", false);
        String ACCESS_TOKEN = AccessTokenTool.getAppAccessToken();
        String URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + ACCESS_TOKEN;
        OutputStream os = null;
        BufferedInputStream bis = null;
        PrintWriter printWriter = null;
        try {
            URL url = new URL(URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            printWriter.write(data.toJson());
            printWriter.flush();
            bis = new BufferedInputStream(httpURLConnection.getInputStream());
            os = new FileOutputStream(new File(savepath));
            int len;
            byte[] arr = new byte[2048];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
            bis.close();
        } catch (Exception e) {
            path = null;
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) bis.close();
                if (printWriter != null) printWriter.close();
                if (os != null) os.close();
            } catch (Exception e) {

            }
        }
        return path;
    }

    /**
     * 取小程序 推广二唯码
     * 不限次数
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
     *
     * @param path
     * @param secne
     * @param
     * @return
     */
    public static String getAppQrCodePath(String path, String secne, String savepath) {
        return getAppQrCodePath(path, secne, savepath, "release", false);
    }

    /**
     * 取得短链接
     *
     * @param page_url
     * @param page_title
     * @return
     */
    public static String getSortLink(String page_url, String page_title) {
        String url = "https://api.weixin.qq.com/wxa/genwxashortlink?access_token=" + AccessTokenTool.getAppAccessToken();
        System.out.println(url);
        Jmode data = Jmode.n().set("page_url", page_url)
                .set("page_title", page_title)
                .set("is_permanent", true);
        Map<String, String> headers = new HashMap<String, String>(16);
        headers.put("Content-Type", "application/json");
        String result = HttpKit.post(url, null, data.toJson(), headers);
        System.out.println(result);
        Map o = JSON.parseObject(result, Map.class);

        if ("0".equals(StringUtil.getString(o, "errcode"))) {
            return StringUtil.getString(o, "link");
        }
        return null;
    }

    /**
     * 取得短信中可拉起的链接
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html
     * <p/>
     * 该接口用于获取小程序 scheme 码，适用于短信、邮件、外部网页、微信内等拉起小程序的业务场景。
     * 目前仅针对国内非个人主体的小程序开
     *
     * @param page_url
     * @param page_title
     * @return
     */
    public static String getGenerateScheme(String page_url, String page_title) {
        String access_token = AccessTokenTool.getAppAccessToken();
        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + access_token;
        System.out.println(url);
        Jmode data = Jmode.n()
                .set("access_token", access_token)
                .set("is_expire", true)
                .set("expire_type", 1)
                .set("expire_time", 1)
                .set("expire_interval", 30)
                .set("jump_wxa", Jmode.n()
                                .set("path", "pages/index/index")
                                .set("query", "")
                                .set("env_version", "release")
                );
        System.out.println(data.toJson());
        Map<String, String> headers = new HashMap<String, String>(16);
        headers.put("Content-Type", "application/json");
        String result = HttpKit.post(url, null, data.toJson(), headers);
        System.out.println(result);
        Map o = JSON.parseObject(result, Map.class);

        if ("0".equals(StringUtil.getString(o, "errcode"))) {
            return StringUtil.getString(o, "link");
        }
        return null;
    }

    /**
     * 正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
     *
     * @param arg
     */
    public static void main(String[] arg) {
        //String UUID = UUIDHex.getUUIDHex();
        //String result = AppTool.getAppQrCodePath("pages/promotion/year2024/index", "243444n5ht8lm3z4xewoihoihvyj7z", "/3.jpg", "trial");
        // String result = AppTool.getAppQrCodePath("hd/vote/vote1", "1", "/vote_trial.png", "trial", true);
        //生成二维码
        String result = AppTool.getAppQrCodePath("pages/questionaire/detail", "1001", "/qnr_1001_release.jpg", "release", false);
        //  System.out.println(result);
       // System.out.println(getGenerateScheme("pages/index/index", "title"));
//        System.out.println(msgSecCheck("pages/index/index", "title"));
    }
}
